import request from "@/services/interceptors";
import { logout } from "@/store/indext";
import { ProForm, ProFormText } from "@ant-design/pro-components";
import { Form, message } from "antd";

interface EditPasswordProps {
  oldPass: string;
  newPass: string;
  confirmNewPass: string; // 添加确认密码字段类型
}
const EditPassword = () => {
  const [form] = Form.useForm<EditPasswordProps>();
  return (
    <div className="w-[600px]">
      <ProForm<EditPasswordProps>
        title="修改登陆密码"
        labelCol={{ span: 4 }}
        layout="horizontal"
        form={form}
        autoFocusFirstInput
        onFinish={async (values) => {
          // 提交时不需要 confirmNewPass 字段
          const { oldPass, newPass } = values;
          await request.sgks.teacherChangeOwnPassCreate({ oldPass, newPass });
          message.success("修改成功, 请重新登录");
          logout();
        }}
      >
        <ProFormText.Password
          rules={[{ required: true, message: "请输入原密码!" }]}
          name="oldPass"
          label="原密码"
        />
        <ProFormText.Password
          rules={[{ required: true, message: "请输入新密码!" }]}
          name="newPass"
          label="新密码"
        />
        {/* 添加确认新密码输入框 */}
        <ProFormText.Password
          name="confirmNewPass"
          label="确认新密码"
          rules={[
            { required: true, message: "请再次输入新密码!" },
            // 添加自定义校验规则
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue("newPass") === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error("两次输入的密码不一致!"));
              },
            }),
          ]}
          // 依赖 newPass 字段，当 newPass 变化时会重新触发表单校验
          dependencies={["newPass"]}
        />
      </ProForm>
    </div>
  );
};

export default EditPassword;
